package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    private static Integer Integer = 0;
    @RequestMapping("/check")
    public Result login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map){
        Jedis resource = jedisPool.getResource();
        //获取请求ip
        String ip = request.getRemoteAddr();
        String visitTimes = resource.get(ip);
        if (visitTimes != null){
            int i = Integer.parseInt(visitTimes);
            if (i > 3){
                resource.close();
                Integer=0;
                return new Result(false,"访问次数受限,请稍后再试");
            }
        }
        //获取请求域数据
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //获取Redis中的验证码
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //验证码校验成功
            //根据电话号码查询数据库中是否有该会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null){
                //数据库中没有该会员,进行静默注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //创建cookie对象,返回客户端
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            //将cookie保存到Redis中
            String json = JSON.toJSON(cookie).toString();
            resource.setex(telephone,1800,json);
            resource.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } else {
            //验证码校验失败
            resource.setex(ip,60,Integer++ + 1 +"");
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
